﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using Ext.Net;
using Ext.Net.MVC;
using com.subb.WebFramework;
using WebEntities;
using WebEntities.Models.Framework;

namespace WebAdmin.Controllers
{
    [Authorize]
    public class MemberController : Controller
    {
        private const string HEADPIC_PATH = "HeadPic/";

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAllMembers(StoreRequestParameters parms, byte memType)
        {
            FW_MemberDAL mdal = new FW_MemberDAL();
            int ttlCount;
            List<FW_Member> dbmemlist = mdal.GetAllMembers(memType, parms.Start, parms.Limit, out ttlCount);
            List<Member> memlist = new List<Member>();
            foreach (var dbmem in dbmemlist)
            {
                Member member = Member.AsMember(dbmem);
                memlist.Add(member);
            }
            return this.Store(memlist, ttlCount);
        }

        [HttpPost]
        public ActionResult DeleteMember(List<Member> delMembers)
        {
            try
            {
                FW_MemberDAL mdal = new FW_MemberDAL();
                foreach (var mem in delMembers)
                {
                    mdal.RemoveMember(mem.GID);
                }
                return this.Direct(new { Success = true, Msg = "删除用户成功！" });
            }
            catch (Exception ex)
            {
                return this.Direct(new { Success = false, Msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message });
            }
        }

        public ActionResult NewMemberWindow()
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "新建用户",
                Width = 700,
                Height = 400,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.UserAdd,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("CreateMember"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Render();
            return this.Direct();
        }

        public ActionResult CreateMember()
        {
            return View();
        }

        [HttpPost]
        public FormPanelResult CreateMember(Member v_member)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            FW_MemberDAL mdal = new FW_MemberDAL();
            string memberId = v_member.MemberID.Trim();
            string nickName = v_member.NickName.Trim();

            //检查用户ID
            int result1 = CheckMemberID(memberId);
            string msg1 = string.Empty;
            switch (result1)
            {
                case -1:
                    msg1 = "用户ID只能英文字母或数字结尾，请重新填写！";
                    break;
                case -2:
                    msg1 = "用户ID只能以字母开头！";
                    break;
                case -3:
                    msg1 = "用户ID已存在，请重新填写！";
                    break;
            }
            if (result1 < 0)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", msg1));
                return response;
            }

            //检查用户昵称
            int result2 = CheckNickName(nickName);
            string msg2 = string.Empty;
            switch (result2)
            {
                case -1:
                    msg2 = "用户昵称不能全是数字，请重新填写！";
                    break;
                case -2:
                    msg2 = "用户昵称已存在，请重新填写！";
                    break;
            }
            if (result2 < 0)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", msg2));
                return response;
            }

            try
            {
                //新建用户
                v_member.HeadPic = string.Empty;
                mdal.CreateMember(v_member);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb = fb.Get("HeadPic");
                    string savePath = string.Empty;
                    if (fpfb != null && fpfb.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + HEADPIC_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb.FileName);
                            savePath += v_member.MemberID + extName;
                            fpfb.SaveAs(savePath);
                            //更新头像路径
                            string webpath = uploadVFolder + HEADPIC_PATH + v_member.MemberID + extName;
                            Member updMember = Member.AsMember(mdal.GetMember(v_member.MemberID));
                            updMember.HeadPic = webpath;
                            mdal.UpdateMember(updMember.GID, updMember);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "用户创建成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        public ActionResult EditMemberWindow(string gid)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "编辑用户",
                Width = 700,
                Height = 400,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.User,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("EditMember"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Loader.Params.Add(new Parameter("gid", gid));
            wnd.Render();
            return this.Direct();
        }

        public ActionResult EditMember(string gid)
        {
            FW_MemberDAL mdal = new FW_MemberDAL();
            FW_Member dbmem = mdal.GetMemberByGID(gid);
            Member member = Member.AsMember(dbmem);
            return View(member);
        }

        [HttpPost]
        public ActionResult EditMember(Member member)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            FW_MemberDAL mdal = new FW_MemberDAL();
            FW_Member fwmember = mdal.GetMemberByGID(member.GID);
            if (!fwmember.MemberID.Equals(member.MemberID, StringComparison.CurrentCultureIgnoreCase))
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", "参数有错误，用户更新失败！"));
                return response;
            }

            //检查用户昵称
            int result1 = CheckNickName(member.NickName.Trim());
            string msg1 = string.Empty;
            if (result1 == -1)
            {
                msg1 = "用户昵称不能全是数字，请重新填写！";
            }
            else if (result1 == -2 && !member.MemberID.Equals(fwmember.MemberID, StringComparison.CurrentCultureIgnoreCase))
            {
                msg1 = "用户昵称已存在，请重新填写！";
            }
            else
            {
                //如果改用户昵称的话，在这里重置result1变量
                result1 = 0;
            }
            if (result1 < 0)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", msg1));
                return response;
            }

            try
            {
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb = fb.Get("HeadPicFile");
                    string savePath = string.Empty;
                    if (fpfb != null && fpfb.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + HEADPIC_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb.FileName);
                            savePath += member.MemberID + extName;
                            fpfb.SaveAs(savePath);
                            //更新头像路径
                            string webpath = uploadVFolder + HEADPIC_PATH + member.MemberID + extName;
                            member.HeadPic = webpath;
                        }
                    }
                }
                mdal.UpdateMember(member.GID, member);
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "用户更新成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        [NonAction]
        private int CheckMemberID(string memberId)
        {
            int result = 0;
            FW_MemberDAL mdal = new FW_MemberDAL();
            char letter1 = memberId.Substring(0, 1).ToCharArray()[0];
            byte bchar1 = (byte)letter1;
            //检查结尾字符
            Regex regex1 = new Regex("[0-9a-zA-Z]+$");
            if (!regex1.IsMatch(memberId))
            {
                //用户ID只能英文字母或数字结尾
                result = -1;
            }
            else if (!((bchar1 >= 65 && bchar1 <= 90) || (bchar1 >= 97 && bchar1 <= 122)))
            {
                //用户ID只能以字母开头
                result = -2;
            }
            else if (mdal.HasExistMemberID(memberId))
            {
                //用户ID已存在
                result = -3;
            }
            return result;
        }

        [NonAction]
        private int CheckNickName(string nickName)
        {
            int result = 0;
            FW_MemberDAL mdal = new FW_MemberDAL();
            //检查昵称是否纯数字
            Regex regex1 = new Regex("^[0-9]+$");
            if (regex1.IsMatch(nickName))
            {
                result = -1;
            }
            else if (mdal.HasExistNickName(nickName))
            {
                result = -2;
            }
            return result;
        }
    }
}
